package com.example.demo.control;


import com.example.demo.model.Result;
import com.example.demo.model.user;
import com.example.demo.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class userController {

    @Autowired
    private userService userService;

    @GetMapping("/index")
    public String index(Model model){
        return "index";
    }
    @PostMapping("/api/user/login")
    public String login(@RequestParam("userName") String userName, @RequestParam("pwd") String pwd, HttpServletRequest request, Model model){
        Result<user> result = userService.login(userName,pwd);

        if (result!=null && result.isSuccess()){
            request.getSession().setAttribute("userId",result.getData().getUid());
            request.getSession().setAttribute("userName",userName);
            return "redirect:/index";
        }

        return "login";
    }
    @GetMapping("/user/login")
    public String login(){
        return "login";
    }
    @PostMapping("/api/user/reg")
    public String reg(@RequestParam("userName") String userName, @RequestParam("password")String pwd,
                      @RequestParam("age") int age,@RequestParam("phone")String phone,@RequestParam("money") double money){
        Result<user> result = userService.register(userName,pwd,age,phone,money);

        if (result!=null && result.isSuccess()){
            return "login";
        }

        return "reg";
    }
    @GetMapping("/user/reg")
    public String register(){
        return "reg";
    }

    @GetMapping("/user/logout")
    @ResponseBody
    public Result logout(HttpServletRequest request){
        Result result = new Result();
        request.getSession().removeAttribute("userId");
        result.setSuccess(true);
        return result;
    }
    @PostMapping("/logout")
    public String logouts(HttpServletRequest request){
        if (request.getSession().getAttribute("userId")==null){
            return "login";
        }
        return "index";
    }
}
